package com.example.demo.test;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author 张述江
 * @date 2023-08-25
 */
@Slf4j
public class DynamicConfig implements ApplicationContextAware {

    @Resource
    private SqlSessionFactory sqlSessionFactory;
    private ApplicationContext applicationContext;
    @Value("${dynamic.jar:/}")
    private String dynamicJar;

    @Bean
    public ModuleApplication moduleApplication() {
        return new ModuleApplication();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 随便找个事件ApplicationStartedEvent，⽤来reload外部的jar，其实直接在moduleApplication()⽅法也可以做
     * 这件事，但是为了验证容器初始化后再加载扩展包还可以⽣效，所以故意放在了这⾥。
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "dynamic", name = "jar")
    public ApplicationListener<ApplicationStartedEvent> applicationListener1(ModuleApplication moduleApplication) {
        return event -> {
            try {
                /*
                 * 加载外部扩展jar
                 */
                moduleApplication.reloadJar(new File(dynamicJar).toURI().toURL());
            } catch (Exception e) {
                log.error("", e);
            }
        };
    }
}
